//
//  MyEmotionToolBar.m
//  WeChat
//
//  Created by ibokan on 16/2/24.
//  Copyright © 2016年 Mac. All rights reserved.
//

#import "YJEmotiontabBar.h"
#import "UIButton+Webcache.h"
#import "YJEmotionTabBarBtn.h"
#import <ImageIO/ImageIO.h>

@interface YJEmotiontabBar()
@property(nonatomic,weak)UIScrollView *scrollView;
@property(nonatomic,weak)UIButton *selectBtn;
@property(nonatomic,weak)UIButton *addBtn;
@property(nonatomic,strong)NSMutableArray  *emotionIconBtns;
@property(nonatomic,weak)UIView *topLine;
@property(nonatomic,weak)UIView *verticalLine;
@property(nonatomic,strong)NSMutableArray  *emotionIcons;
@end
#define ADDBUTTONWIDTH 47
@implementation YJEmotiontabBar
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.emotionIconBtns = [NSMutableArray array];
        
        UIView *topLine = [[UIView alloc]init];
        topLine.backgroundColor = kUIColorFromRGB(0xeaeaea);
        [self addSubview:topLine];
        self.topLine = topLine;
        
        UIView *verticalLine = [[UIView alloc]init];
        verticalLine.backgroundColor = kUIColorFromRGB(0xeaeaea);
        [self addSubview:verticalLine];
        self.verticalLine = verticalLine;
        
        //表情包添加按钮
        UIButton *addBtn = [[UIButton alloc]init];
        [addBtn setImage:Image(@"emotionTabBar_add_icon") forState:UIControlStateNormal];
        [addBtn addTarget:self action:@selector(addBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:addBtn];
        self.addBtn = addBtn;
        //表情
        [self createBtnWithEmotionIcons];
        
        [NOTIFICATIONCENTER addObserver:self selector:@selector(emotionListDidChange) name:YJEmotionListDidChangeNotification object:nil];
    }
    return self;
}

- (UIScrollView *)scrollView
{
    if (_scrollView == nil)
    {
        UIScrollView *scrollView = [[UIScrollView alloc]init];
        scrollView.showsHorizontalScrollIndicator = NO;
        scrollView.showsHorizontalScrollIndicator = NO;
        [self addSubview:scrollView];
        self.scrollView = scrollView;
    }
    return _scrollView;
}

- (void)createBtnWithEmotionIcons
{
    for (UIButton *btn in self.emotionIconBtns)
      [btn removeFromSuperview];
    [self.emotionIconBtns removeAllObjects];
    
    self.emotionIcons = [@[@"emotionTabBar_default_icon",@"emotionTabBar_collection_icon"] mutableCopy];

    //添加网络下载表情包部分
    NSString *emotionFilePath = LIBFILEPATH(@"emotionIcons.archive");
    NSArray *downloadEmotions = [NSKeyedUnarchiver unarchiveObjectWithFile:emotionFilePath];
    if (downloadEmotions.count > 0)
    {
        [self.emotionIcons addObjectsFromArray:downloadEmotions];
    }
    
    [self.emotionIcons enumerateObjectsUsingBlock:^(id _Nonnull emotionIcon, NSUInteger index, BOOL * _Nonnull stop) {
        YJEmotionTabBarBtn *btn = [[YJEmotionTabBarBtn alloc]init];
        if (index < self.emotionIcons.count - downloadEmotions.count)
          [btn setImage:[UIImage imageNamed:emotionIcon] forState:UIControlStateNormal];
        else
        {
           [btn sd_setImageWithURL:[NSURL URLWithString:emotionIcon[@"iconUrl"]] forState:UIControlStateNormal completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
               
               if (error || !image) return;
               //获取gif图片的第一帧
               NSString *fileUrl = [[SDImageCache sharedImageCache] defaultCachePathForKey:emotionIcon[@"iconUrl"]];
               UIImage *fisrtImage =  [self firstImageWithGifPath:fileUrl];
               [btn setImage:fisrtImage forState:UIControlStateNormal];
           }];
            btn.teamId = emotionIcon[@"teamId"];
        }

        [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        btn.tag = index + 10;
        if (index == 0)
        {
            btn.enabled = NO;
            self.selectBtn = btn;
        }
        [self.scrollView addSubview:btn];
        [self.emotionIconBtns addObject:btn];
    }];
}

//获取gif第一张图片
- (UIImage *)firstImageWithGifPath:(NSString *)gifPath {
    NSURL *fileUrl = [NSURL fileURLWithPath:gifPath];
    CGImageSourceRef gifSource = CGImageSourceCreateWithURL((CFURLRef)fileUrl, NULL);
    CGImageRef imageRef = CGImageSourceCreateImageAtIndex(gifSource, 0, NULL);
    UIImage *image = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
    return image;
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    self.scrollView.x = ADDBUTTONWIDTH;
    self.scrollView.y = 0;
    self.scrollView.height = self.height;
    self.scrollView.width = self.width - self.scrollView.x;
    
    self.topLine.x = 0;
    self.topLine.y = 0;
    self.topLine.height = 1;
    self.topLine.width = self.width;
    
    self.verticalLine.x = ADDBUTTONWIDTH;
    self.verticalLine.y = 3;
    self.verticalLine.height = self.height - 2 * self.verticalLine.y;
    self.verticalLine.width = 1;
    
    CGFloat btnH = self.height;
    CGFloat btnW = btnH + 13;
    self.addBtn.x = 0;
    self.addBtn.y = 0;
    self.addBtn.width = ADDBUTTONWIDTH;
    self.addBtn.height = btnH;
    
    NSUInteger count = self.emotionIconBtns.count;
    for (int i = 0; i < count; i ++)
    {
        YJEmotionTabBarBtn *btn = self.emotionIconBtns[i];
        btn.width = btnW;
        btn.height = btnH;
        btn.x = i * btnW;
        btn.y = 0;
    }
    self.scrollView.contentSize = CGSizeMake(count * btnW, 0);
}

-(void)btnAction:(YJEmotionTabBarBtn *)btn
{
    self.selectBtn.enabled = YES;
    btn.enabled = NO;
    self.selectBtn = btn;
    if (self.tabBarButtonBlock)
    {
        self.tabBarButtonBlock(btn);
    }
}

- (void)emotionListDidChange
{
    [self createBtnWithEmotionIcons];
    [self btnAction:self.emotionIconBtns.firstObject];
    //重新布局表情键盘
    [self setNeedsLayout];
}

- (void)addBtnClick
{
    [NOTIFICATIONCENTER postNotificationName:YJEmotiontabBarAddNotification object:nil];
}

-(void)dealloc
{
    [NOTIFICATIONCENTER removeObserver:self];
}

@end
